package com.nexgo.payment.action.transresp;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nexgo.payment.R;
import com.nexgo.payment.action.Action;
import com.nexgo.payment.action.ActionResult;
import com.nexgo.payment.action.ActionStep;
import com.nexgo.payment.action.OnActionListener;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.Repository;
import com.nexgo.payment.databases.TransRecord;
import com.nexgo.payment.fragment.ProgressDialogFragment;
import com.nexgo.payment.fragment.TextDialogFragment;
import com.nexgo.payment.ui.BaseFragment;
import com.nexgo.payment.util.MessageHelper;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.ToastUtils;
import com.nexgo.payment.util.TransUtils;
import com.nexgo.payment.util.UIUtils;
import com.nexgo.payment.widget.ItemLinearLayout;
import com.nexgo.payment.widget.TitleBuilder;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import java8.util.Optional;

/**
 * 交易结果显示界面
 * 并在此界面打印签购单
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年8月16日
 */
public class TransRespFragment extends BaseFragment implements Action<ActionStep>, TransRespContract.View, BaseFragment.DownTimerListener {
    //交易结果描述
    @BindView(R.id.tv_resp_desc)
    TextView tvRespDesc;
    //交易抬头背景：成功-绿色、失败-红色
    @BindView(R.id.linear_title)
    LinearLayout linearTitle;
    //商户名称
    @BindView(R.id.item_merchant_name)
    ItemLinearLayout mMerchantName;
    //商户编号
    @BindView(R.id.item_merchant_no)
    ItemLinearLayout mMerchantNo;
    //终端编号
    @BindView(R.id.item_terminal_no)
    ItemLinearLayout mTerminalNo;
    //操作员编号
    @BindView(R.id.item_op_no)
    ItemLinearLayout mOpNo;
    //交易类型
    @BindView(R.id.item_trade_type)
    ItemLinearLayout mTradeType;
    //卡号
    @BindView(R.id.item_card_no)
    ItemLinearLayout mCardNo;
    //支付码号
    @BindView(R.id.item_pay_code_no)
    ItemLinearLayout mPayCodeNo;
    //付款凭证码
    @BindView(R.id.item_pay_trace_code)
    ItemLinearLayout mPayTraceCode;
    //参考号
    @BindView(R.id.item_refer_no)
    ItemLinearLayout mReferNo;
    //批次号
    @BindView(R.id.item_batch_no)
    ItemLinearLayout mBatchNo;
    //流水号
    @BindView(R.id.item_trace_num)
    ItemLinearLayout mTraceNum;
    //交易时间
    @BindView(R.id.item_date_time)
    ItemLinearLayout mTradeTime;
    //交易金额
    @BindView(R.id.item_trade_amount)
    ItemLinearLayout mTradeAmount;
    //返回主菜单
    @BindView(R.id.btn_back_2_main)
    Button btnBack2Main;

    Unbinder unbinder;

    private OnActionListener mListener;
    private TransRespContract.Presenter mPresenter;
    private ProgressDialogFragment mDialogFragment;

    public TransRespFragment() {
    }

    public static TransRespFragment newInstance() {
        TransRespFragment fragment = new TransRespFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TransRespPresenter(this, Repository.getInstance());
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_trans_resp, container, false);
        unbinder = ButterKnife.bind(this, view);

        initTitle(view);

        return view;
    }

    /**
     * 初始化标题栏
     *
     * @param view
     */
    private void initTitle(View view) {
        new TitleBuilder(view)
                .setLeftImage(R.drawable.arrow_icon)
                .setTitleText(getString(R.string.resp_title))
                .build();
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.start();
    }

    @OnClick({R.id.title_iv_left, R.id.btn_back_2_main})
    public void onClicked(View view) {
        if (UIUtils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.title_iv_left:
            case R.id.btn_back_2_main:
                cancelDownTimer();  //先取消倒计时
                if (mListener != null) {
                    mListener.setActionResult(new ActionResult(TransRespFragment.this, ActionResult.SUCC, null));
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnActionListener) {
            mListener = (OnActionListener) context;
        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        cancelDownTimer();
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.destroy();
    }

    @Override
    public ActionStep getActionStep() {
        return ActionStep.PRINT_RECEIPT;
    }

    @Override
    public void setPresenter(TransRespContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showTransResp(TransRecord transRecord) {
        //设置显示界面抬头背景颜色及描述
        linearTitle.setBackgroundColor(getResources().getColor(R.color.trans_success_color));
        //根据响应码显示提示语
        String respDesc = MessageHelper.getResponseCodeErrorInfo(transRecord.getRespCode());
        Log.d("showTransResp", "showTransResp: " + respDesc);
        tvRespDesc.setText(TextUtils.isEmpty(respDesc) ? getString(R.string.resp_trans_success) : respDesc);
        //商户名称
        mMerchantName.setRightText(transRecord.getMerchantName());
        //商户编号
        mMerchantNo.setRightText(transRecord.getMerchantId());
        //终端编号
        mTerminalNo.setRightText(transRecord.getTerminalId());
        //操作员号
        Optional.ofNullable(transRecord.getOperator())
                .filter(integer -> integer != 0)
                .ifPresent(integer -> {
                    mOpNo.setVisibility(View.VISIBLE);
                    mOpNo.setRightText(String.format(SysConstant.LOCALE, "%02d", integer));
                });
        //交易类型
        mTradeType.setRightText(TransType.values()[transRecord.getTransType()].getName());
        //卡号
        Optional.ofNullable(transRecord.getPan())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    mCardNo.setVisibility(View.VISIBLE);
                    mCardNo.setRightText(TransUtils.maskPan(s));
                });
        //支付码号（扫码相关）
        Optional.ofNullable(transRecord.getPayCodeNo())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    mPayCodeNo.setVisibility(View.VISIBLE);
                    mPayCodeNo.setRightText(TransUtils.maskPan(s));
                });
        //付款凭证码（扫码相关）
        Optional.ofNullable(transRecord.getPayTraceCode())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    mPayTraceCode.setVisibility(View.VISIBLE);
                    mPayTraceCode.setRightText(s);
                });
        //参考号
        Optional.ofNullable(transRecord.getRefNum())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    mReferNo.setVisibility(View.VISIBLE);
                    mReferNo.setRightText(s);
                });
        //批次号
        Optional.ofNullable(transRecord.getBatchNum())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    mBatchNo.setVisibility(View.VISIBLE);
                    mBatchNo.setRightText(s);
                });
        //流水号
        Optional.ofNullable(transRecord.getTraceNum())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    mTraceNum.setVisibility(View.VISIBLE);
                    mTraceNum.setRightText(s);
                });
        //交易时间
        if (!TextUtils.isEmpty(transRecord.getDate()) && !TextUtils.isEmpty(transRecord.getTime())) {
            mTradeTime.setVisibility(View.VISIBLE);
            mTradeTime.setRightText(StringUtils.formatDateTime(transRecord.getDate(), transRecord.getTime()));
        }
        //交易金额
        Optional.ofNullable(transRecord.getAmount())
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> {
                    mTradeAmount.setVisibility(View.VISIBLE);
                    mTradeAmount.setRightText(StringUtils.formatAmount(s, SysConstant.FUND_DIGITS));
                });
    }

    @Override
    public void showPrintInitErr() {
        ToastUtils.showToast(getString(R.string.print_err));
    }

    @Override
    public void setPrintingIndicator(boolean active) {
        if (active) {
            if (mDialogFragment == null) {
                mDialogFragment = new ProgressDialogFragment();
            }
            mDialogFragment.setTipTitle(getString(R.string.printing));
            mDialogFragment.setTip(getString(R.string.pls_wait));
            mDialogFragment.setCancelable(false);
            mDialogFragment.show(getActivity().getSupportFragmentManager(), null);
        } else {
            if (mDialogFragment != null && mDialogFragment.getDialog() != null) {
                Dialog dialog = mDialogFragment.getDialog();
                if (dialog.isShowing()) {
                    mDialogFragment.dismiss();
                }
                mDialogFragment = null;
            }
        }
    }

    @Override
    public void showPrintSuccess() {
        setDownTimer(SysConstant.TIME_OUT_10, this);
    }

    @Override
    public void showPrintLackPaper() {
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.print_lack_paper));
        dialogFragment.setContentText(getString(R.string.print_lack_desc), Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.confirm));
        dialogFragment.setNegativeText(getString(R.string.cancel));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {
                showPrintSuccess();
            }

            @Override
            public void onConfirm() {
                mPresenter.startPrint();
            }
        });
        dialogFragment.show(getActivity().getSupportFragmentManager(), null);
    }

    @Override
    public void showConfirmPrintAgain() {
        //打印第一联完成后调用
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.kindly_tip));
        dialogFragment.setContentText(getString(R.string.continue_print), Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.confirm), SysConstant.TIME_OUT_5);
        dialogFragment.setNegativeText(getString(R.string.cancel));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {
                showPrintSuccess();
            }

            @Override
            public void onConfirm() {
                mPresenter.startPrint();
            }
        });
        dialogFragment.show(getActivity().getSupportFragmentManager(), null);
    }

    @Override
    public void showPrintFail(String failDesc) {
        Optional.ofNullable(failDesc)
                .filter(s -> !TextUtils.isEmpty(s))
                .ifPresent(s -> ToastUtils.showToast(s));
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @Override
    public void onTick(long secondsUntilFinished) {
        if (!isActive()) {
            return;
        }
        btnBack2Main.setText(getString(R.string.back_to_main_layout) + "（" + secondsUntilFinished + "）");
    }

    @Override
    public void onFinish() {
        if (isActive()) {
            btnBack2Main.setText(getString(R.string.back_to_main_layout) + "（0）");
        }
        //自动返回主菜单
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(TransRespFragment.this, ActionResult.SUCC, null));
        }
    }
}
